package com.ahs.aspect;

import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;
import java.util.Arrays;

/**
 * @author riven zhang
 * @since 2021/4/29 16:39
 */
@Aspect
@Component
@Slf4j
public class CacheClear {

    private static final String[] NON_CLEAR = {"select", "query", "clear", "fuzzySearch"};


    @Pointcut("@within(com.ahs.annotation.CacheClear)")
    public void pointCut() {
    }

    @AfterReturning("pointCut()")
    public void clear(JoinPoint point) throws Throwable {
        // 执行方法调用
        log.info("执行方法调用");
        MethodSignature signature = (MethodSignature) point.getSignature();
        String methodName = signature.getMethod().getName();
        // 如果不是查询的方法，则清空缓存
        if (Arrays.stream(NON_CLEAR).noneMatch(methodName::contains)) {
            Class<?> clazz = point.getThis().getClass();
            // AOP执行缓存清理
            Method clear = clazz.getMethod("clear");
            clear.invoke(clazz);
            log.info("AOP执行缓存清理");
        }
    }
}
